package cn.hk.controller;

import cn.HK.po.User;
import cn.HK.utils.CookieUtils;
import cn.HK.vo.SystemResult;
import cn.hk.service.EditService;
import cn.hk.service.LoginService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class LoginController {
    /*
 * 登陆
请求路径：/user/login
请求方式:post
请求参数User
返回值类型：User
*/
    @Autowired(required = false)
    private LoginService loginService;
    @RequestMapping(value = "/login")
    public SystemResult doLogin(User user, HttpServletResponse response,
                                HttpServletRequest request){
        //调用业务层代码,获取返回的redis的key值
        //key值如果为空,说明业务层没有登录成功
        String ticket=loginService.doLogin(user);//redis的key值
        if(StringUtils.isEmpty(ticket)){
            //为空说明登录失败,返回失败对象
            return SystemResult.build(201,"登录失败",null);
        }else{
            //登录成功了 将ticket 存放到cookie返回给客户端
            CookieUtils.setCookie(
                    request,response,
                    "HK1_TICKET",//这里的cookieName必须是EM_TICKET
                    ticket);
            return SystemResult.ok();
        }
    }
    /*
    * 查询状态
请求路径：/user/status
请求方式:get
请求参数_ticket
返回值类型：User
*/
    @RequestMapping(value = "/status" ,method = RequestMethod.GET)
    public User queryUserJson(String ticket){
        User user=loginService.queryUserJson(ticket);
        //userJson可能为空 超时了就拿不到该数据
       return user;
    }
    /*修改个人信息
请求路径：/change
请求方式:
请求参数：User//匹配 uPassword//写入
返回值类型：SystemResult
*/
    @Autowired(required = false)
    private EditService editService;
    @RequestMapping(value = "/change")
    public SystemResult edituser(User user,String newPassword){
        try {
            editService.editUser(user,newPassword);
            return SystemResult.ok();
        }catch (Exception e){
            e.printStackTrace();
            return SystemResult.build(201,"个人信息修改失败",null);
        }
    }
}
